# Copyright (c) 2018 Presto Labs Pte. Ltd.
# Author: leon

import datetime

import pandas
from pandas.io.sql import to_sql
from tabulate import tabulate

from coin.strategy.mm.subscription import get_subscription_key
from coin.support.feed_tool.feed_stats.logic.util import *
from coin.support.feed_tool.feed_stats.logic.instrument_stats_calculator import (
    BitmexInstrumentStatsCalculator, OkexInstrumentStatsCalculator, InstrumentStats)
from coin.support.feed_tool.feed_stats.logic.db_instrument_stats_calculator import (
    DbInstrumentStatsCalculator)


class DbDumpStrategy(object):
  def __init__(self, machine, trading_date: datetime.datetime, subscription_request):
    self._machine = machine
    self._trading_date = trading_date
    self._exchange = subscription_request.exchange
    assert self._exchange == 'Okex'
    self._subscription_request = subscription_request
    self._db_instrument_stats_calculator = None

  def update_db_instrument_to_calculator(self):
    if self._exchange == 'Okex':
      self._db_instrument_stats_calculator = DbInstrumentStatsCalculator(
          self._trading_date, self._machine, self._subscription_request)
      self._db_instrument_stats_calculator.extract_feed_from_db()

  def print_instrument_stats(self):
    assert self._db_instrument_stats_calculator is not None
    self._db_instrument_stats_calculator.calculator_stats()
    stats_table = self._db_instrument_stats_calculator.instrument_stats
    if len(stats_table) == 0:
      print('No instrument feed stats for this run!')
    else:
      print(tabulate(stats_table, headers=InstrumentStats._fields))

  def dump_to_db(self, db_config_path):
    assert self._db_instrument_stats_calculator is not None
    engine = gen_engine_for_importer()
    self._db_instrument_stats_calculator.calculator_stats()
    stats = self._db_instrument_stats_calculator.instrument_stats
    df = pandas.DataFrame(stats, columns=InstrumentStats._fields)
    to_sql(df, 'InstrumentStats', engine, if_exists='append', index=False)

  def generate_csv(self, output_csv_root):
    assert self._db_instrument_stats_calculator is not None
    self._db_instrument_stats_calculator.generate_csv(output_csv_root)
